package com.fnd.servicechat.controller;

import com.alibaba.fastjson.JSON;
import com.fnd.servicechat.models.UUser;
import com.fnd.servicechat.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;


/**
 * @Description 用户控制类
 * @Author Administrator
 * @Date 2019/11/15 10:18
 * @Version 1.0
 */
@Controller
@RequestMapping("/user")
public class UserController {
    @Autowired
    private IUserService userService;

    @RequestMapping("/")
    public String login(){
        return "/login";
    }

    @RequestMapping("/login")
    public ModelAndView login(HttpServletRequest request, HttpServletResponse response) throws IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html; charset=utf-8");
        PrintWriter out=response.getWriter();
        UUser uUser = userService.login(request.getParameter("username"), request.getParameter("password"));
        if(uUser.getId() < 1){
            out.print("<script>alert('用户名或者密码错误，请重新登录');history.go(-1);</script>");
            return null;
        }
        ModelAndView modelView = new ModelAndView();
        Cookie cookie = new Cookie("userIds", uUser.getId()+"");
        Cookie cookie2 = new Cookie("userNames", uUser.getuName());
        Cookie cookie3 = new Cookie("userUrls", uUser.getuUrl());
        response.addCookie(cookie);
        response.addCookie(cookie2);
        response.addCookie(cookie3);
        modelView.setViewName("/chatroom");
        return modelView;
    }

    /**
     * 获取好友列表信息
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/get_userinfo")
    public String index(HttpServletRequest request){
        return JSON.toJSONString(userService.getAllUser(request.getParameter("id")));
    }


    /**
     * 获取群组
     * @param id
     * @return
     */
    @ResponseBody
    @RequestMapping("/groupInfo")
    public List<Map> groupInfoByUserId(Integer id){
        return userService.getGroupByUserId(id);
    }


}
